package com.htkj.questservice;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;

public class ForegroundAppMonitorService extends Service {
    private static final int NOTIFICATION_ID = 1001;
    private static final int POLL_INTERVAL = 5000; // 5秒轮询一次
    private Handler handler;
    private Runnable pollTask;

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler(Looper.getMainLooper());
        pollTask = new Runnable() {
            @Override
            public void run() {
                checkForegroundApp();
                handler.postDelayed(this,  POLL_INTERVAL);
            }
        };
    }

    private void checkForegroundApp() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            String packageName = ForegroundAppDetector.getForegroundApp(this);
            Log.d("ForegroundApp", "当前应用: " + packageName);
            // 发送广播或通知其他组件
        }
    }

    @SuppressLint("ForegroundServiceType")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 必须在前台通知就绪后再执行其他逻辑
        startForeground(NOTIFICATION_ID, buildNotification());
        checkForegroundApp(); // 你的业务逻辑
        handler.post(pollTask);
        return START_STICKY; // 服务被杀死后自动重启
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private Notification buildNotification() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
        }
        return new NotificationCompat.Builder(this, "foreground_channel")
                .setContentTitle("应用监控运行中")
                .setContentText("正在检测前台应用变化")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel(
                "foreground_channel",
                "应用监控服务",
                NotificationManager.IMPORTANCE_LOW
        );
        getSystemService(NotificationManager.class).createNotificationChannel(channel);
    }
}
